package com.p2p.front.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.p2p.base.exception.BizException;
import com.p2p.base.util.DateUtil;
import com.p2p.front.dal.model.Finance;
import com.p2p.front.service.FinanceService;
import com.p2p.front.service.LoanInfoService;
import com.p2p.front.service.TenderReturnService;

@Service("realTimeFinance")
public class RealTimeFinance extends BaseTask {

	@Resource
	private LoanInfoService loanInfoService;

	@Resource
	private FinanceService financeService;

	@Resource
	private TenderReturnService tenderReturnService;

	@Scheduled(cron = "0 0 3  * *  ?")
	// 每天早上三点执行
	public void getRealTimeFinanceSchedule() throws ParseException {
		if(!this.doTaskSynchronous(this.getBizKey(), 20)){
			return;
		}

		try {
			doBiz();
		} catch (Exception e) {
			logger.error("",e);
		}
		this.doRmoveTaskSynchronous(this.getBizKey());
	}

	public void doBiz(){

		Finance finance = financeService.getLatestFinance();
		Date lastUpdateDate;
		if(finance!=null){
			lastUpdateDate = DateUtil.addDay(new Date(), -2);
		}else{
			try {
				lastUpdateDate = DateUtil.parseStandardDate(finance.getDate());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new BizException("TIME_FORMAT_ERROR","时间格式转换错误！");
			}
		}
		
		int days = 0;
		Date endDate = DateUtil.addDay(new Date(), -1);
		try {
			days = DateUtil.getDayBetweenTwoDate(endDate,lastUpdateDate );
		} catch (Exception e) {
			throw new BizException("TIME_FORMAT_ERROR","时间格式转换错误！");
		}

		if (days > 1) {
			// 跑定时器间隔大于一天 另外处理
			for (int i = days; i > 0; i--) {
				Calendar cal = Calendar.getInstance();
				cal.add(Calendar.DATE, -i);
			/*	String date = new SimpleDateFormat("yyyy-MM-dd ").format(cal
						.getTime());*/
				String dateStr = DateUtil.getDateStr(cal.getTime());
				try {
					financeService.getFinanceData(dateStr);
				} catch (ParseException e) {
					e.printStackTrace();
					throw new BizException("TIME_FORMAT_ERROR","时间格式转换错误！");
				}
			}
		} else if (days == 1) {
			// 正常情况 定时器每天跑一次 统计昨天一天的数据
			Calendar cal = Calendar.getInstance();
			cal.add(Calendar.DATE, -1);
			String yesterday = new SimpleDateFormat("yyyy-MM-dd ").format(cal
					.getTime());
			try {
				financeService.getFinanceData(yesterday);
			} catch (ParseException e) {
				e.printStackTrace();
				throw new BizException("TIME_FORMAT_ERROR","时间格式转换错误！");
			}

		} else {//

		}
	}
	@Override
	public String getBizKey() {
		String bizKey = "task_RealTimeFinanceSchedule_";
		return bizKey;
	}

}
